package com.vastcom.action;

import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.vastcom.model.Department;
import com.vastcom.model.Resource;
import com.vastcom.model.Role;
import com.vastcom.model.Roleresource;
import com.vastcom.model.Users;
import com.vastcom.service.ManageService;
import com.vastcom.service.RcService;
import com.vastcom.vo.RightTreeVo;
@Namespace("/rbac")
public class LoginAction extends BaseAction {
	
	private Users user;
	private String page;
	private String rows;
	private Role role;
	private Department dept;
	private String deptid;
	private String yonghuming;
	private String newpass;
	private String oldpass;
	private Resource resources;
	private String type;
	private String roleid;
	private Roleresource roleresource;
	private String kaptcha;
	
	
	


	
	@Autowired
	private RcService rcservice;
	@Autowired
	private ManageService manageservice;
	
	
	
	public String getKaptcha() {
		return kaptcha;
	}

	public void setKaptcha(String kaptcha) {
		this.kaptcha = kaptcha;
	}

	public Roleresource getRoleresource() {
		return roleresource;
	}

	public void setRoleresource(Roleresource roleresource) {
		this.roleresource = roleresource;
	}

	public String getRoleid() {
		return roleid;
	}

	public void setRoleid(String roleid) {
		this.roleid = roleid;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Resource getResources() {
		return resources;
	}

	public void setResources(Resource resources) {
		this.resources = resources;
	}

	public String getNewpass() {
		return newpass;
	}

	public void setNewpass(String newpass) {
		this.newpass = newpass;
	}

	public String getOldpass() {
		return oldpass;
	}

	public void setOldpass(String oldpass) {
		this.oldpass = oldpass;
	}

	public String getYonghuming() {
		return yonghuming;
	}

	public void setYonghuming(String yonghuming) {
		this.yonghuming = yonghuming;
	}

	public String getDeptid() {
		return deptid;
	}

	public void setDeptid(String deptid) {
		this.deptid = deptid;
	}

	public Department getDept() {
		return dept;
	}

	public void setDept(Department dept) {
		this.dept = dept;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}
	
	
	
	@Action("login")
	public String login() throws Exception{
		
		//从session中取出的验证码
		String kaptchaExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); 
		
		if (kaptcha == null || !kaptchaExpected.equalsIgnoreCase(kaptcha)){  
		     json.put("msg", "errorkaptcha");
		     this.setJsonString(json.toString());
		     return "json";
		} 
		
		
		
		//调用SHIRO的登录接口
		Subject subject =SecurityUtils.getSubject();
		//生成令牌环
		AuthenticationToken token = new UsernamePasswordToken(user.getUsername(),user.getPass());
		
		try {
			subject.login(token);
			Users u=rcservice.getUserByUsernameAndPassword(user.getUsername(), user.getPass());
			ActionContext.getContext().getSession().put("roleid", u.getRoleid());
			ActionContext.getContext().getSession().put("users", u);
			String deptname=manageservice.getDeptNameById(u.getDpid());
			ActionContext.getContext().getSession().put("deptname", deptname);
			ActionContext.getContext().getSession().put("usersName", u.getUsername());
			json.put("msg", "ok");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	
	@Action("getAllRole")
	public String getAllRole() throws Exception{
		int intPage = Integer.parseInt((page == null || page.equals("0") ? "1" : page));
		int num = Integer.parseInt((rows == null || rows.equals("0") ? "10" : rows));
		int start = (intPage - 1) * num;
		
		List<Role> rl=rcservice.getRoleList(start, num);
		
		json.put("total", manageservice.CountTableSize("Role"));
		json.put("rows", rl);
		this.setJsonString(json.toString());
		return "json";

	}
	
	@Action("addRole")
	public String addRole() throws Exception{
		boolean flag=rcservice.addRole(role);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	
	@Action("deleteRole")
	public String deleteRole() throws Exception{
		boolean flag=rcservice.deleteRole(role);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	@Action("getSingleRole")
	public String getSingleRole() throws Exception{
		
		Role r=rcservice.getRole(role);
		if(r!=null){
			json.put("msg", r);
		}
		else{
			json.put("msg", "error");
		}
		
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	
	@Action("updateRole")
	public String updateRole() throws Exception{
		
		boolean flag=rcservice.updateRole(role);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	
	@Action("getAlldepartment")
	public String getAlldepartment() throws Exception{
		List<Department> dl=manageservice.getDepartmentList();
		
		if(dl.size()>0){
			json.put("rows", dl);
		}
		else{
			json.put("msg", 0);
		}
		
		this.setJsonString(json.toString());
		return "json";
		
		
	}
	
	@Action("addDept")
	public String addDept() throws Exception{
		boolean flag=manageservice.addDepartment(dept);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		
		this.setJsonString(json.toString());
		return "json";
	}
	
	@Action("getSingleDepartment")
	public String getSingleDepartment() throws Exception{
		Department d=manageservice.getDepartment(dept);
		if(d!=null){
			json.put("msg", d);
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	
	@Action("updateDepartment")
	public String updateDepartment() throws Exception{
		boolean flag=manageservice.updateDepartment(dept);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	
	@Action("deleteDept")
	public String deleteDept() throws Exception{
		boolean flag=manageservice.deleteDepartment(dept);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	@Action("getUsersBydeptid")
	public String getUsersBydeptid() throws Exception{
		
		int intPage = Integer.parseInt((page == null || page.equals("0") ? "1" : page));
		int num = Integer.parseInt((rows == null || rows.equals("0") ? "10" : rows));
		int start = (intPage - 1) * num;
		
		
		List<Users> ul=rcservice.getUsersByDept(deptid);
		for(Users u:ul){
			u.setRoleid(rcservice.getRoleNameById(u.getRoleid()));
		}
		
		json.put("total", ul.size());
		json.put("rows", ul);
		this.setJsonString(json.toString());
		return "json";
		
	}
	
	@Action("addUsers")
	public String addUsers() throws Exception{
		boolean flag=rcservice.addUser(user);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	
	@Action("getSingleUser")
	public String getSingleUser() throws Exception{
		Users u=rcservice.getUser(user);
		if(u!=null){
			json.put("msg", u);
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	@Action("updateUser")
	public  String updateUser() throws Exception{
		boolean flag=rcservice.updateUser(user);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	
	@Action("deleteUser")
    public String deleteUser() throws Exception{
		boolean flag=rcservice.deleteUser(user);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}	
	
	
	
	@Action("checkUsername")
	public String checkUsername() throws Exception{
		Users u=rcservice.getUserByUsername(yonghuming);
		Writer w=response.getWriter();
		
		if(u!=null){
			w.write("false");
		}
		else{
			w.write("true");
		}
		return null;
	}
	
	@Action("getallRoleforSel")
	public String getallRoleforSel() throws Exception{
		List<Role> rl=rcservice.getRoleList();
		if(rl.size()>0){
			json.put("msg", rl);
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
		
	}
	//用户的登出操作
	@Action("logOut")
	public String logOut() throws Exception{
		Subject subject =SecurityUtils.getSubject();
		if(subject!=null){
			subject.logout();
			response.sendRedirect("/login.jsp");
		}
		return null;
		
	}
	
	//密码修改
	
	@Action("changePassWord")
	public String changePassWord() throws Exception{
		//在session中获取登录的用户名
		String username=(String)ActionContext.getContext().getSession().get("usersName");
		Users u=rcservice.getUserByUsernameAndPassword(username, oldpass);
		if(u!=null){
			u.setPass(newpass);
			rcservice.updateUser(u);
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		
		this.setJsonString(json.toString());
		return "json";
		
		
	}
	
	
	
	@Action("getMenuTree")
	public String getMenuTree() throws Exception{
		
		List<Resource> rl=rcservice.getResourceListByType(type);
		jsonArray.addAll(rl);
		this.setJsonString(jsonArray.toString());
		return "json";
		
	}
	
	@Action("addMenu")
	public String addMenu() throws Exception{
		boolean flag=rcservice.addResource(resources);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
			
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	@Action("updateMenu")
	public String updateMenu() throws Exception{
		boolean flag=rcservice.updateResource(resources);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	@Action("deleteMenu")
	public String deleteMenu() throws Exception{
		boolean flag=rcservice.deleteResource(resources);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	
	@Action("getAction")
	public String getAction() throws Exception{
		Resource r=rcservice.getResource(resources);
		if(r!=null){
			json.put("msg", r);
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
	}
	
	@Action("getResourceByRoleid")
	public String getResourceByRoleid() throws Exception{
		List<Resource> rl=rcservice.getResourceListByType(type);
		List<RightTreeVo> rtvl=new ArrayList<RightTreeVo>();
		for(Resource r:rl){
			RightTreeVo v=new RightTreeVo();
			if(rcservice.hasResource(roleid, r.getId())){
				v.setChecked("true");
			}
			else{
				v.setChecked("false");
			}
			v.setId(r.getId());
			v.setName(r.getName());
			v.setOpen("false");
			v.setPath(r.getPath());
			v.setPid(r.getPid());
			rtvl.add(v);
		}
		
		jsonArray.addAll(rtvl);
		
		this.setJsonString(jsonArray.toString());
		return "json";
		
		
		
		
	}
	
	//授权
	@Action("addRoleResources")
	public String addRoleResources() throws Exception{
		
		boolean flag=rcservice.addRoleresource(roleresource);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		this.setJsonString(json.toString());
		return "json";
		
	}
	//取消授权
	@Action("deleteRoleResources")
	public String deleteRoleResources() throws Exception{
		
		boolean flag=rcservice.deleteRoleresource(roleresource);
		if(flag){
			json.put("msg", "ok");
		}
		else{
			json.put("msg", "error");
		}
		
		this.setJsonString(json.toString());
		return "json";
		
		
	}
	
	@Action("getResourceByRoleidForUser")
	public String getResourceByRoleidForUser() throws Exception{
		
		
		String roleids=(String)ActionContext.getContext().getSession().get("roleid");
		
		List<Resource> rl=rcservice.getResourceListByType(type);
		List<RightTreeVo> rtvl=new ArrayList<RightTreeVo>();
		for(Resource r:rl){
			
			if(rcservice.hasResource(roleids, r.getId())){
				RightTreeVo v=new RightTreeVo();
				v.setId(r.getId());
				v.setName(r.getName());
				v.setOpen("false");
				v.setPath(r.getPath());
				v.setPid(r.getPid());
				rtvl.add(v);
			}
			
			
		}
		
		jsonArray.addAll(rtvl);
		
		this.setJsonString(jsonArray.toString());
		return "json";
		
	}
	
	
	@Action("testPasswordService")
	public String testPasswordService() throws Exception{
		PasswordService passwordservice=new DefaultPasswordService();
//		//数据字段加密
//		String encode=passwordservice.encryptPassword("123456");
//		json.put("encode", encode);
//		
//		//数据是否匹配
//		boolean flag=passwordservice.passwordsMatch("123456", encode);
//		json.put("flag", flag);
		Users u=rcservice.getUserById("40281f8150a9b9210150a9bd544f0005");
		if(u!=null){
			u.setPass(passwordservice.encryptPassword("1"));
			rcservice.updateUser(u);
		}
		
		this.setJsonString(json.toString());
		return "json";
		
		
		
	}

	
	
	
	
	

}
